<template>
  <div id="mall">
    <div class="mallsearch"><search
      @on-change="getResult"
      :results="results"
      placeholder="商品名称/积分数量"
      v-model="searchtxt"
      position="static"
      auto-scroll-to-top top="0"
      @on-focus="onFocus"
      @on-cancel="onCancel"
      @on-submit="onSubmit"
      ref="searchtalk"></search></div>
    <swiper class="mallswiper" auto :list="swiperlist" dots-position="center" :aspect-ratio="280/750" dots-class="activedots"></swiper>
    <div class="flexgrid">
      <div class="flexitem" @click="routeto('productlist', {type: 'all'})">
        <img slot="icon" src="../assets/images/mall-type-icon(5).png">
        <p slot="label" class="div-center">所有兑换</p>
      </div>
      <div class="flexitem" @click="routeto('productlist', {type: 'canbeinto'})">
        <img slot="icon" src="../assets/images/mall-type-icon(3).png">
        <p slot="label" class="div-center">可兑换</p>
      </div>
      <div class="flexitem" @click="routeto('productlist', {type: 'entity'})">
        <img slot="icon" src="../assets/images/mall-type-icon(4).png">
        <p slot="label" class="div-center">实物</p>
      </div>
      <div class="flexitem" @click="routeto('productlist', {type: 'coupon'})">
        <img slot="icon" src="../assets/images/mall-type-icon(1).png">
        <p slot="label" class="div-center">优惠券</p>
      </div>
      <div class="flexitem" @click="routeto('productlist', {type: 'curriculum'})">
        <img slot="icon" src="../assets/images/mall-type-icon(6).png">
        <p slot="label" class="div-center">课程</p>
      </div>
    </div>
    <div class="hotlist">
      <div class="hottitle">—— 热门兑换 ——</div>
      <div class="hotol">
        <div class="hotli" v-for="(item, index) in hotlist" :key="index" @click="routeto('productdetail', {id: item.id})">
          <div class="imgarea">
            <img :src="item.img">
          </div>
          <p class="hotlititle">{{item.title}}</p>
          <div class="hotliprice"><span>{{item.price}}</span>积分<a href="javascript:;" @click.stop="toBuy(index)">兑换</a></div>
        </div>
      </div>
    </div>
    <div class="hotmore" @click="routeto('productlist', {type: 'all'})">查看更多</div>
    <!-- <div class="hotmore" @click="routeto('producthot')">查看更多</div> -->
    <div class="fixedbar">
      <div class="item cookiecar" @click="routeto('orderbuycar')">
        <img src="../assets/images/buycar(1).png"><br>
        <span>收藏夹</span>
      </div>
      <div class="item cookiecar" @click="routeto('points')">
        <p>{{pointsinfo.lastpoints}}</p>
        <span>我的积分</span>
      </div>
      <div class="item cookiecar" @click="routeto('orderlist')">
        兑换记录
      </div>
    </div>
    <div id="searchlist" v-show="showsearch">
      <scroller class="" height="-44" scrollbar-y lock-x @on-scroll-bottom="onScrollTalkBottom" slot="searchslot" ref="allsearch">
        <div class="searcharr" name="searchslot">
          <cell :title="aitem.title" @click.native="routeto('productdetail', { id: aitem.id })" :border-intent="false" v-for="(aitem, aindex) in talklists" :key="aindex">
            <div class="searchdesc" slot="after-title"><span class="hotcolor">{{ aitem.price }}</span>积分<a href="javascript:;" @click.stop="fastToBuy(aindex)">兑换</a></div>
            <img class="searchimg" slot="icon" :src="aitem.img" alt="">
          </cell>
          <load-more :value="isloadtalk" :show-loading="isloadtalk" :tip="loadtip" style="margin: .5rem auto;">Loading</load-more>
        </div>
      </scroller>
    </div>
    <loading :show="buyloadtoast" :text="'加载中...'"></loading>
    <confirm v-model="isshowgetcard"
      title="提示"
      content="您现在还不是微信会员，请先领取微信会员卡"
      :close-on-confirm="false"
      @on-cancel="cancelGetCard"
      @on-confirm="showVipCard">
    </confirm>
    <confirm v-model="showconfirm"
      :content="confirmtxt"
      :close-on-confirm="false"
      @on-cancel="cancelConfirm"
      @on-confirm="okConfirm">
    </confirm>
    <confirm v-model="showfastconfirm"
      :content="fastconfirmtxt"
      :close-on-confirm="false"
      @on-cancel="cancelFastConfirm"
      @on-confirm="okFastConfirm">
    </confirm>
    <div transfer-dom>
      <alert v-model="erralert">{{erralerttext}}</alert>
    </div>
  </div>
</template>

<script>
import Swiper from 'vux/src/components/swiper/swiper.vue'
import SearchList from '@/pages/SearchList'
import { Alert, Search, Cell, XButton, Tab, TabItem, Badge, LoadMore, Scroller, Confirm, Loading } from 'vux'
export default{
  name: 'mall',
  components: {
    Alert,
    Swiper,
    SearchList,
    Search,
    Cell,
    XButton,
    Badge,
    Tab,
    TabItem,
    LoadMore,
    Scroller,
    Confirm,
    Loading
  },
  data () {
    return {
      swiperlist: [],
      hotlist: [],
      pointsinfo: {},
      showsearch: false,
      isshowmore: false,
      isloadtalk: false,
      onFetching: false,
      erralert: false,
      erralerttext: '',
      talkUpList: [],
      talklists: [],
      seachTalkList: [],
      results: [],
      searchtxt: '',
      loadtip: '',
      buyloadtoast: false,
      isshowgetcard: false,
      showconfirm: false,
      confirmtxt: '',
      fastarr: '',
      showfastconfirm: false,
      fastconfirmtxt: '',
      fastfastarr: ''
    }
  },
  created () {
    this.$axios.post(this.apidomain + '/api/member/getIsActivateMemberCard/' + this.getCookie('appid'), {
      openId: this.getCookie('openid')
    })
    .then((response) => {
      if (response.data.data === '1') {
        this.$axios.post(this.apidomain + '/api/integralMall/hotProductInfo/' + this.getCookie('appid'), {
          num: 4
        })
        .then((response) => {
          this.hotlist = response.data.data
        })
        // get swiper list
        this.$axios.post(this.apidomain + '/api/integralMall/queryBannerInfo/' + this.getCookie('appid'), {})
        .then((response) => {
          this.swiperlist = response.data.data
        })
        // 拉取积分数据
        this.$axios.post(this.apidomain + '/api/integralMall/getIntegralSum/' + this.getCookie('appid'), {
          openId: this.getCookie('openid')
        })
        .then((response) => {
          this.pointsinfo = response.data.data
        })
        .catch(function (error) {
          console.log(error)
        })
      } else {
        // this.routeto('wechatticket')
        this.isshowgetcard = true
      }
    })
  },
  methods: {
    toBuy: function (index) {
      let buyinfo = this.hotlist[index]
      this.fastarr = buyinfo
      if (buyinfo.type === '1') {
        this.confirmtxt = '本次兑换将消耗' + 1 * buyinfo.price + '积分，兑换成功后可至兑换记录页面查看，确认兑换吗？'
        this.showconfirm = true
      } else {
        this.routeto('productdetail', {id: buyinfo.id})
      }
    },
    getList: function (txt) {
      return this.$axios.post(this.apidomain + '/api/integralMall/queryProductInfoListSearch/' + this.getCookie('appid'), {
        pageIndex: this.talklists.length,
        openId: this.getCookie('openid'),
        name: txt
      })
      .then((response) => {
        return response.data.data
      })
      .catch(function (error) {
        console.log(error)
        return []
      })
    },
    onScrollTalkBottom () {
      if (this.onFetching) {
        if (!this.isloadtalk && this.searchtxt !== '') {
          this.isloadtalk = true
          this.loadtip = '加载中'
          this.getList(this.searchtxt)
          .then((data) => {
            this.talklists.push.apply(this.talklists, data)
          }, () => {})
          this.$nextTick(() => {
            this.$refs.allsearch.reset()
          })
          setTimeout(() => {
            this.isloadtalk = false
            this.loadtip = ''
          }, 1000)
        } else {
          this.$nextTick(() => {
            this.$refs.allsearch.reset()
          })
        }
      } else {
        this.onFetching = true
        setTimeout(() => {
          this.onFetching = false
        }, 1000)
      }
    },
    getResult (val) {
      this.talklists = []
      this.searchtxt = val
      if (val.length > 0) {
        window.zhuge.track('Click', {
          '事件名称': '会员中心-积分商城-搜索-点击',
          '搜索内容': val,
          'OpenID': this.getCookie('openid'),
          '点击时间': (new Date().toLocaleString())
        })
      }
      // 发生变化
      if (val !== '') {
        this.getList(val)
        .then((data) => {
          this.talklists = data
        }, () => {})
        this.$nextTick(() => {
          this.$refs.allsearch.reset({top: 0})
        })
      }
    },
    onSubmit () {
      this.$refs.searchtalk.setBlur()
      this.$vux.toast.show({
        type: 'text',
        position: 'top',
        text: 'on submit'
      })
    },
    onFocus () {
      this.showsearch = true
    },
    onCancel () {
      this.showsearch = false
      this.searchtxt = ''
      this.talklists = []
      setTimeout(() => {
        this.$nextTick(() => {
          this.$refs.allsearch.reset({top: 0})
        })
      }, 100)
    },
    fastToBuy: function (index) {
      let buyinfo = this.talklists[index]
      this.fastfastarr = buyinfo
      if (buyinfo.type === '1') {
        this.fastconfirmtxt = '本次兑换将消耗' + 1 * buyinfo.price + '积分，兑换成功后可至兑换记录页面查看，确认兑换吗？'
        this.showfastconfirm = true
      } else {
        this.routeto('productdetail', {id: buyinfo.id})
      }
    },
    showVipCard () {
      // 未领取会员卡
      this.$axios.post(this.apidomain + '/api/card/getWxCardId/' + this.getCookie('appid'), {
        cardType: 'MEMBER_CARD'
      })
      .then((response) => {
        const timestamp = Date.parse(new Date()) / 1000
        const nonceStr = Math.random().toString(36).substr(2)
        this.getObjDetail(this.apidomain + '/api/wechat/mp/getCardApiTicket/' + this.getCookie('appid'))
        .then((data) => {
          const noncearr = [timestamp, response.data.data.cardId, data.data, nonceStr]
          noncearr.sort()
          const signature = this.$jssha(noncearr.join(''))
          this.$wechat.ready(() => {
            this.$wechat.addCard({
              cardList: [{
                cardId: response.data.data.cardId,
                cardExt: '{"timestamp": "' + timestamp + '", "nonce_str": "' + nonceStr + '", "signature": "' + signature + '"}'
              }],
              success: (res) => {
                this.isshowgetcard = false
                setTimeout(() => {
                  window.location.reload()
                }, 1500)
              },
              cancel: (error) => {
                console.log(error)
                window.alert('亲爱的用户，您还没有激活会员卡哦！')
                window.WeixinJSBridge.invoke('closeWindow')
              }
            })
            if (navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1) {
              // 监听是否点击关闭原生卡
              document.addEventListener('visibilitychange', () => {
                if (document.visibilityState !== 'hidden') {
                  window.WeixinJSBridge.invoke('closeWindow')
                }
              })
            }
          })
        }, () => {})
      })
    },
    cancelGetCard () {
      window.WeixinJSBridge.invoke('closeWindow')
    },
    cancelConfirm: function () {
      this.showconfirm = false
    },
    okConfirm: function () {
      this.showconfirm = false
      this.buyloadtoast = true
      window.zhuge.track('Click', {
        '事件名称': '会员中心-积分商城-热门兑换商品-兑换-点击',
        '商品名称': this.fastarr.title,
        'OpenID': this.getCookie('openid'),
        '点击时间': (new Date().toLocaleString())
      })
      let sdata = [{
        'id': this.fastarr.id,
        'num': 1,
        'weight': ''
      }]
      this.$axios.post(this.apidomain + '/api/integralMall/saveConfirmOrder/' + this.getCookie('appid'), {
        data: sdata,
        openId: this.getCookie('openid'),
        name: '',
        phone: '',
        address: '',
        province: '',
        city: '',
        district: ''
      })
      .then((response) => {
        this.buyloadtoast = false
        if (response.data.errorCode === '0') {
          window.zhuge.track('Click', {
            '事件名称': '会员中心-积分商城-热门兑换商品-兑换-提交订单-点击',
            '商品名称': this.fastarr.title,
            '商品金额': this.fastarr.price,
            'OpenID': this.getCookie('openid'),
            '点击时间': (new Date().toLocaleString())
          }, () => {
            this.routeto('orderdetail', {id: response.data.data.id})
          })
        } else {
          this.erralerttext = response.data.errorMsg
          this.erralert = true
        }
      })
    },
    cancelFastConfirm: function () {
      this.showfastconfirm = false
    },
    okFastConfirm: function () {
      this.showfastconfirm = false
      this.buyloadtoast = true
      let sdata = [{
        'id': this.fastfastarr.id,
        'num': 1,
        'weight': ''
      }]
      this.$axios.post(this.apidomain + '/api/integralMall/saveConfirmOrder/' + this.getCookie('appid'), {
        data: sdata,
        openId: this.getCookie('openid'),
        name: '',
        phone: '',
        address: '',
        province: '',
        city: '',
        district: ''
      })
      .then((response) => {
        this.buyloadtoast = false
        if (response.data.errorCode === '0') {
          this.routeto('orderdetail', {id: response.data.data.id})
        } else {
          this.erralerttext = response.data.errorMsg
          this.erralert = true
        }
      })
    }
  }
}
</script>
<style lang="less">
@import '../assets/less/product/mall.less';
</style>
